<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
            background-color: #f5f5f5;
        }
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: white;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            max-width: 800px;
            margin: 20px auto;
            border-radius: 10px;
            overflow: hidden;
        }
        .tabs {
            display: flex;
            background-color: #007bff;
        }
        .tab {
            flex: 1;
            padding: 15px;
            text-align: center;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .tab.active {
            background-color: #0056b3;
        }
        .tab:hover {
            background-color: #004080;
        }
        .chat-history {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column;
            animation: fadeIn 0.5s;
        }
        .message-bubble {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 10px;
            position: relative;
        }
        /* 用户Tab样式 */
        .chat-container[data-active-tab="user"] .message.user-a {
            align-items: flex-end;
        }
        .chat-container[data-active-tab="user"] .message.user-b {
            align-items: flex-start;
        }
        .chat-container[data-active-tab="user"] .message.user-a .message-bubble {
            background-color: #007bff;
            color: white;
            border-bottom-right-radius: 0;
            border-bottom-left-radius: 10px;
        }
        .chat-container[data-active-tab="user"] .message.user-b .message-bubble {
            background-color: #e1e1e1;
            color: black;
            border-bottom-left-radius: 0;
            border-bottom-right-radius: 10px;
        }
        /* 客服Tab样式 */
        .chat-container[data-active-tab="customer"] .message.user-a {
            align-items: flex-start;
        }
        .chat-container[data-active-tab="customer"] .message.user-b {
            align-items: flex-end;
        }
        .chat-container[data-active-tab="customer"] .message.user-a .message-bubble {
            background-color: #e1e1e1;
            color: black;
            border-bottom-left-radius: 0;
            border-bottom-right-radius: 10px;
        }
        .chat-container[data-active-tab="customer"] .message.user-b .message-bubble {
            background-color: #007bff;
            color: white;
            border-bottom-right-radius: 0;
            border-bottom-left-radius: 10px;
        }
        .message-timestamp {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        .input-container {
            display: flex;
            padding: 10px;
            background-color: white;
            border-top: 1px solid #ddd;
        }
        .input-container input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }
        .input-container button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .input-container button:hover {
            background-color: #0056b3;
        }
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
<div class="chat-container" data-active-tab="user">
    <div class="tabs">
        <div class="tab active" id="tab-user" onclick="switchTab('user')">用户</div>
        <div class="tab" id="tab-customer" onclick="switchTab('customer')">客服</div>
    </div>

    <div class="chat-history" id="chat-history"></div>

    <div class="input-container" id="input-user">
        <input type="text" id="user-input" placeholder="用户输入消息">
        <button onclick="sendMessage('user-a')">发送</button>
    </div>

    <div class="input-container" id="input-customer" style="display: none;">
        <input type="text" id="customer-input" placeholder="客服输入消息">
        <button onclick="sendMessage('user-b')">发送</button>
    </div>
</div>

<script>
    const socket = new WebSocket('ws://localhost:8080/ws');
    let heartbeatInterval;
    const HEARTBEAT_INTERVAL = 1000; // 1秒

    socket.onopen = function(event) {
        console.log('WebSocket 连接已建立');
        appendMessage('系统', 'WebSocket 连接成功！', 'system');

        // 启动心跳定时器
        startHeartbeat();
    };

    socket.onmessage = function(event) {
        const data = JSON.parse(event.data);

        // 处理心跳响应消息
        if (data.message === 'HEARTBEAT_RESPONSE') {
            console.log('[心跳接收] 收到服务器心跳响应', new Date().toLocaleTimeString());
            return;
        }

        console.log('[消息接收]', data.sender, data.message, new Date().toLocaleTimeString());
        appendMessage(data.sender, data.message, data.sender);
    };

    socket.onclose = function(event) {
        console.log('WebSocket 连接关闭');
        appendMessage('系统', 'WebSocket 连接已关闭，请刷新页面重试！', 'system');

        // 清除心跳定时器
        stopHeartbeat();
    };

    socket.onerror = function(event) {
        console.error('WebSocket 发生错误:', event);
    };

    function sendMessage(sender) {
        const inputId = sender === 'user-a' ? 'user-input' : 'customer-input';
        const input = document.getElementById(inputId);
        const message = input.value.trim();

        if (message && socket.readyState === WebSocket.OPEN) {
            const data = { sender, message };
            socket.send(JSON.stringify(data));
            console.log('[消息发送]', sender, message, new Date().toLocaleTimeString());
            appendMessage(sender, message, sender);
            input.value = '';
        } else {
            alert('消息不能为空或连接未打开！');
        }
    }

    function appendMessage(sender, message, className) {
        const chatHistory = document.getElementById('chat-history');
        const messageElement = document.createElement('div');
        messageElement.classList.add('message', className);

        const bubble = document.createElement('div');
        bubble.classList.add('message-bubble');
        bubble.textContent = message;

        const timestamp = document.createElement('div');
        timestamp.classList.add('message-timestamp');
        timestamp.textContent = new Date().toLocaleTimeString();

        messageElement.appendChild(bubble);
        messageElement.appendChild(timestamp);
        chatHistory.appendChild(messageElement);
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }

    function switchTab(tab) {
        const chatContainer = document.querySelector('.chat-container');
        document.getElementById('tab-user').classList.remove('active');
        document.getElementById('tab-customer').classList.remove('active');
        document.getElementById('input-user').style.display = 'none';
        document.getElementById('input-customer').style.display = 'none';

        if (tab === 'user') {
            document.getElementById('tab-user').classList.add('active');
            document.getElementById('input-user').style.display = 'flex';
            chatContainer.setAttribute('data-active-tab', 'user');
        } else {
            document.getElementById('tab-customer').classList.add('active');
            document.getElementById('input-customer').style.display = 'flex';
            chatContainer.setAttribute('data-active-tab', 'customer');
        }
    }

    // 启动心跳定时器
    function startHeartbeat() {
        console.log('[心跳启动] 开始发送心跳消息，间隔:', HEARTBEAT_INTERVAL, 'ms');
        heartbeatInterval = setInterval(() => {
            if (socket.readyState === WebSocket.OPEN) {
                const heartbeatMessage = {
                    sender: 'system',
                    message: 'HEARTBEAT'
                };
                socket.send(JSON.stringify(heartbeatMessage));
                console.log('[心跳发送] 发送心跳消息', new Date().toLocaleTimeString());
            } else {
                console.warn('[心跳发送] 连接未就绪，状态:', socket.readyState);
            }
        }, HEARTBEAT_INTERVAL);
    }

    // 停止心跳定时器
    function stopHeartbeat() {
        if (heartbeatInterval) {
            console.log('[心跳停止] 停止心跳定时器');
            clearInterval(heartbeatInterval);
            heartbeatInterval = null;
        }
    }

    // 页面关闭前清理资源
    window.addEventListener('beforeunload', () => {
        stopHeartbeat();
        if (socket.readyState === WebSocket.OPEN) {
            socket.close();
        }
    });
</script>
</body>
</html>